import {PlusOutlined, EyeOutlined} from '@ant-design/icons';
import {ActionType, ProColumns, ProTable} from '@ant-design/pro-components';
import {Button, message, Popconfirm, Space, Tag} from 'antd';
import React, {useRef, useState} from 'react';
import {
  addQuestionAPI, addQuestionOptionAPI,
  deleteQuestionAPI, pageQuestionAPI,
  updateQuestionAPI,
} from './service';
import QuestionForm from './components/QuestionForm';
import QuestionDetail from './components/QuestionDetail';
import QuestionOptionForm from './components/QuestionOptionForm';
import {downloadFileUrl} from "@/services/system/file";
import {listLicenseTypeAPI} from "@/pages/license-type/services";
import {listCourseSubjectAPI} from "@/pages/course-subject/services";
import {listQuestionTypeAPI} from "@/pages/question/question-type/services";

const QuestionManagement: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentQuestion, setCurrentQuestion] = useState<API.IQuestion | null>();

  // 查看详情
  const handleViewDetail = async (question: API.IQuestion) => {
    setCurrentQuestion(question);
    setDetailVisible(true);
  };

  // 表格列配置
  const columns: ProColumns<API.IQuestion>[] = [
    {
      title: '题目内容',
      dataIndex: 'content',
      key: 'content',
      ellipsis: true,
    },
    {
      title: '题目类型',
      dataIndex: 'questionType',
      key: 'questionType',
      width: 80,
      valueEnum: {
        '1': {text: '单选'},
        '2': {text: '多选'},
        '3': {text: '判断'},
      },
    },
    {
      title: '分类',
      dataIndex: 'typeId',
      key: 'typeId',
      width: 120,
      valueType: 'select',
      request: async () => {
        const {data} = await listQuestionTypeAPI({status: "0"});
        return (data || []).map((item: API.IQuestionType) => {
          return {
            label: item.name,
            value: item.id,
          }
        })
      },
    },
    {
      title: '驾照类型',
      dataIndex: 'licenseTypeId',
      key: 'licenseTypeId',
      ellipsis: true,
      width: 120,
      render: (_, record) => {
        return `${record.licenseTypeName}(${record.licenseTypeCode})`
      },
      valueType: 'select',
      request: async () => {
        const {data} = await listLicenseTypeAPI({});
        return (data || []).map((item: API.ILicenseType) => {
          return {
            label: `${item.licenseCode}-${item.licenseName}`,
            value: item.id,
          }
        })
      },
    },
    {
      title: '科目',
      dataIndex: 'courseTypeId',
      key: 'courseTypeId',
      ellipsis: true,
      width: 80,
      render: (_, record) => {
        return record.courseSubjectName
      },
      valueType: 'select',
      request: async () => {
        const {data} = await listCourseSubjectAPI({});
        return (data || []).map((item: API.ICourseSubject) => {
          return {
            label: item.subjectName,
            value: item.id,
          }
        })
      },
    },
    {
      title: '难度',
      dataIndex: 'difficulty',
      key: 'difficulty',
      valueEnum: {
        '1': {text: '简单'},
        '2': {text: '中等'},
        '3': {text: '困难'},
      },
      width: 80,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      valueEnum: {
        '0': {text: '启用', status: 'Success'},
        '1': {text: '禁用', status: 'Error'},
      },
    },
    {
      title: '题目来源',
      dataIndex: 'source',
      key: 'source',
      width: 80,
      valueEnum: {
        'ai': {text: 'AI生成'},
        'local': {text: '本地题库'},
      },
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: 200,
      render: (text, record) => [
        <a key="view" onClick={() => handleViewDetail(record)}>
          <EyeOutlined/> 查看
        </a>,
        <QuestionForm
          key="edit"
          formType="edit"
          initialValues={record}
          onFinish={async (values) => {
            const {data} = await updateQuestionAPI({...values, id: record?.id});
            if (data) {
              message.success('修改成功');
              actionRef.current?.reload();
            }
            return data;
          }}
          trigger={<a>编辑</a>}
        />,
        <QuestionOptionForm
          key="addOption"
          formType="create"
          onFinish={async (values) => {
            const {data} = await addQuestionOptionAPI(values as any);
            if (data) {
              message.success('选项添加成功');
            }
            return data;
          }}
          questionId={record.id || ''}
          trigger={<a>添加选项</a>}
        />,
        <Popconfirm
          key="delete"
          title="确定要删除这个题目吗?"
          onConfirm={async () => {
            const {data} = await deleteQuestionAPI(record.id || '');
            if (data) {
              message.success('删除成功');
              actionRef.current?.reload();
            }
            return data;
          }}
          okText="确定"
          cancelText="取消"
        >
          <a style={{color: 'red'}}>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <>
      <ProTable<API.IQuestion>
        headerTitle="题目管理"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          span: 6,
        }}
        pagination={{
          pageSize: 10,
        }}
        toolBarRender={() => [
          <QuestionForm
            key="create"
            formType="create"
            onFinish={async (values) => {
              const {data} = await addQuestionAPI(values);
              if (data) {
                message.success('新增成功');
                actionRef.current?.reload();
              }
              return data
            }}
            trigger={
              <Button type="primary">
                <PlusOutlined/> 新增题目
              </Button>
            }
          />,
        ]}
        request={async (params) => {
          const {data} = await pageQuestionAPI(params);
          return data;
        }}
        columns={columns}
        size={'small'}
      />

      <QuestionDetail
        visible={detailVisible}
        onClose={() => setDetailVisible(false)}
        question={currentQuestion!}
      />
    </>
  );
};

export default QuestionManagement;
